package main

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"math/rand"
	"time"
)

func main() {
	r := gin.Default()
	logger, err := zap.NewProduction()
	if err != nil {
		panic(err)
	}

	//使用中间层，相当于拦截器
	r.Use(func(c *gin.Context){
		t := time.Now()
		c.Next()
		logger.Info("incoming request",
			zap.String("path",c.Request.URL.Path),
			zap.Int("status",c.Writer.Status()),
			zap.Duration("elapsed",time.Now().Sub(t)) )
	}, func(c *gin.Context){
		c.Set("requestId", rand.Int())
		c.Next()
	})

	h := gin.H{
		"message": "pong",
	}


	r.GET("/ping", func(c *gin.Context) {
		if rid,exist := c.Get("requestId"); exist{
			h["requestId"] = rid
		}
		c.JSON(200, h)
	})

	r.GET("/hello", func(c *gin.Context) {
		c.String(200, "ok")
	})

	r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
